// gbk转换工具
const gbk = require('./gbk.js');

/**中文字符串转为GBK对应的十进制编码 */
const hexStringToBuff = str => { //str='中国：WXHSH'
    const buffer = new Array();
    var data = str.toString();
    let dataPara
    for (let i = 0; i < data.length; i++) {
        if (data.charCodeAt(i) < 128) { //如果是英文
            //英文GBK十进制
            dataPara = data[i].charCodeAt(0);
            buffer.push(dataPara);
        } else {
            //调用GBK 转码
            let t = gbk.encode(data[i]);
            //中文GBK十进制
            dataPara = parseInt(String(t).replace(/%/g, ''), 16); // “你” 的GBK编码是 %C4%E3 变成 C4E3 再转换成 50403
            buffer.push(dataPara);
        }
        console.log(data[i] + " 对应的编码===> "+ dataPara);
    }
    return buffer;
}

function toUnicode(s) {
    var str = "";
    for (var i = 0; i < s.length; i++) {
        str += "\\u" + s.charCodeAt(i).toString(16) + "\t";
    }
    return str;
}

function strToHexCharCode(str) {
    if (str === "")
        return "";
    var hexCharCode = [];
    hexCharCode.push("0x");
    for (var i = 0; i < str.length; i++) {
        hexCharCode.push((str.charCodeAt(i)).toString(16));
    }
    return hexCharCode.join("");
}

// 计算长度，中文占两个字节，其他字符占一个字节
function sumStrLength(str) {
    var length = 0;
    var data = str.toString();
    for (var i = 0; i < data.length; i++) {
        if (isCN(data[i])) { //是中文
            length += 2;
        } else {
            length += 1;
        }
    }
    return length;
}

//判断是否是中文，是，true
function isCN(str) {
    if (/^[\u3220-\uFA29]+$/.test(str)) {
        return true;
    } else {
        return false;
    }
}

//汉字转码
function hexStringToArrayBuffer(str) {
    const buffer = new ArrayBuffer((str.length / 2) + 1)
    const dataView = new DataView(buffer)
    for (var i = 0; i < str.length / 2; i++) {
        var temp = parseInt(str[i * 2] + str[i * 2 + 1], 16)
        dataView.setUint8(i, temp)
    }
    dataView.setUint8((str.length / 2), 0x0a)
    return buffer;
}

//返回八位数组
function subString(str) {
    var arr = [];
    if (str.length > 8) { //大于8
        for (var i = 0;
            (i * 8) < str.length; i++) {
            var temp = str.substring(i * 8, 8 * i + 8);
            arr.push(temp)
        }
        return arr;
    } else {
        return str
    }
}

//不带有汉字
function hexStringToArrayBufferstr(str) {
    let val = ""
    for (let i = 0; i < str.length; i++) {
        if (val === '') {
            val = str.charCodeAt(i).toString(16)
        } else {
            val += ',' + str.charCodeAt(i).toString(16)
        }
    }
    val += "," + "0x0a";
    console.log(val)
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
        return parseInt(h, 16)
    })).buffer
}

module.exports = {
    // 汉字转换为GBK编码
    hexStringToArrayBuffer: hexStringToArrayBuffer,
    hexStringToBuff: hexStringToBuff,
}